package com.richman.ps38;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.richman.controller.DecreseRatio;
import com.richman.hg.HGManager;
import com.richman.ps38.entity.Event;
import com.richman.utils.Common;

public class PS38Manager {

	
	public static Vector<Event> ps38Events = new Vector<Event>();
	public Vector<String[]> ratios = new Vector<String[]>();
	public static String ps38UpdateStr = "";
	public static Vector<Event> ps38DanshiEvents = new Vector<Event>();
	public static  ReadWriteLock danshiEventsLock = new ReentrantReadWriteLock();
	
	public Vector<PS38Selenium> accounts = new Vector<PS38Selenium>();
	
	public Vector<PS38Selenium> danshiAccounts = new Vector<PS38Selenium>();
	
	double BASIC_RATIO = 42.385;
	
	BufferedWriter fw = null;  //写	
	BufferedReader reader = null; //读
	
	public void init() {
		Vector<String[]> tmps = DecreseRatio.mainWnd.getPS38Accounts();
		for(int i = 0; i <tmps.size(); i++ ) {
			PS38Selenium ps38Selenium = new PS38Selenium();
			ps38Selenium.setLoginParams(tmps.elementAt(i)[0], tmps.elementAt(i)[1],
					tmps.elementAt(i)[2], tmps.elementAt(i)[3], tmps.elementAt(i)[4]);
			accounts.add(ps38Selenium);
		}
		
		initRatios();
	}
	
	
	

	
	
	public void login() {
		
		
		try {
			
			for(int i = 0; i <accounts.size(); i++ ) {				
				if(accounts.elementAt(i).getStatusCode() == -1) {
								
					accounts.elementAt(i).Login();
					
					
					Thread.sleep(2000);
					
					System.out.println(accounts.elementAt(i).getStatusCode());
					
				}
			}			
		}catch(Exception e) {
			e.printStackTrace();
		}
		

		
	}
	



	public Vector<String[]> getratios(){
		return ratios;
	}

	
	public void grabEvents() {
		
		
		try {
			
			
			
			SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");// 设置日期格式
			
			String showText = "";
			

			String notUsefulText = "";
			
			
			int second = DecreseRatio.mainWnd.getUpdateSeconds();
			
			int usefulAccountNum = 0;
			
			for(int i = 0; i <accounts.size(); i++ ) {
				
				if(accounts.elementAt(i).getStatusCode() != -1 && accounts.elementAt(i).getStatusCode() != 0) {
					usefulAccountNum++;
				}
			}
			
			
			
			if(usefulAccountNum*second < 4000 && usefulAccountNum != 0) {
				second = 4000/usefulAccountNum;
			}
			
			int millis = second;
			
			
			String failstr = " 登录中";
			if(System.currentTimeMillis() - DecreseRatio.startEngineTime > 150*1000) {
				failstr = " 无法获取赛事列表";
			}
			
			
			for(int i = 0; i <accounts.size(); i++ ) {
				
				String successText = "";
				String failText = "";
				
				int statusCode = accounts.elementAt(i).getStatusCode();
				
				if(statusCode != -1 && statusCode != 0) {
					accounts.elementAt(i).getMatches();
				}
				
				
				if(accounts.elementAt(i).getStatusCode() == 3) {
					successText = accounts.elementAt(i).getAccount() + "  " + df.format(System.currentTimeMillis()) + " " + " 获取赛事列表成功" + "\n";
				}else {
					failText = accounts.elementAt(i).getAccount() + "  " + df.format(System.currentTimeMillis()) + " "+ " 获取赛事列表失败" + "\n";
				}
				
				if(!successText.equals("")) {
					showText +=  successText; 
				}
				
				if(failText.equals("")) {
					showText += failText;
				}
				
				
				
				

				DecreseRatio.mainWnd.updatePS38AccountStatus(accounts.elementAt(i).getAccount(), accounts.elementAt(i).getStatusCode());
				
				Thread.sleep(5000);

			}
			
			ps38UpdateStr =showText;
			
			DecreseRatio.mainWnd.updatePS38TextArea(showText);
			
			constructShowItem();
			
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		

		
	}
	
	
	private void constructShowItem() {
		try {			
	        LocalTime currentTime = LocalTime.now();
	        LocalTime compareTime = LocalTime.of(20, 50);	       
	        if (currentTime.isAfter(compareTime)) {
		        for(int i = 0; i < accounts.size(); i++) {
		        	if(accounts.elementAt(i).ratios.size()>1&&accounts.elementAt(i).ratios.elementAt(0)[1].contains("-")) {
		        		Common.logOut("准备封盘,碰到--的情况，不统计");
		        		return;
		        	}
		        }
	        } 
			

	        
			boolean deleteAlready = false;
			boolean allSuccess = true;
			for(int i = 0;i < accounts.size();i++) {
				if(accounts.elementAt(i).getStatusCode()!=3) {
					allSuccess = false;
					break;
				}
			}
			if(allSuccess==false) {
				Common.logOut("not all account grab data success!!!");
				return;
			}
			SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm:ss");// 设置日期格式
			String updateTime = df.format(System.currentTimeMillis());
			for(int j = 0; j<49;j++ ) {//1-49号
				boolean decrease = false;
				String period = "";
				String num = "";
				int decreaseCount = 0;
				String decreseWebCode = "";
				for(int i = 0;i < accounts.size();i++) {
					PS38Selenium account = accounts.elementAt(i);
					if(period.equals("")) {
						period = account.period;
					}
					
					if(account.getStatusCode()==3) {
						num = account.ratios.elementAt(j)[0];
						String value = account.ratios.elementAt(j)[1];
						if(Common.isNum(value)) {
							if(Double.parseDouble(value)<Double.parseDouble(account.BASICRATIO)) {
								if(decreseWebCode.equals("")) {
									decreseWebCode = account.SEARCHCODE;
								}else {
									decreseWebCode = decreseWebCode + "-" + account.SEARCHCODE;
								}
								
								decreaseCount++;
								decrease = true;
							}
						}
						//todo 统计并保存
					}
				}
				
				if(decrease==true) {
					if(deleteAlready==false) {
				        // 使用迭代器遍历并删除特定元素
				        Iterator<String[]> iterator = ratios.iterator();
				        while (iterator.hasNext()) {
				            String[] element = iterator.next();
				            if (period.equals(element[0])) { // 检查是否满足删除条件
				                iterator.remove(); // 使用迭代器的remove方法删除元素
				            }
				        }
						deleteAlready = true;
					}
					String[] ratio = {period,num,Integer.toString(decreaseCount),decreseWebCode,updateTime,""};
					ratios.add(ratio);
				}
				
			}
			saveTofile();
			DecreseRatio.mainWnd.updateHGEventsTable(ratios);

		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void updatePeriodRes(String period, Vector<String> res) {
		try {
			String restmp = "";
			if(res.size()==7) {
				restmp = res.elementAt(0) + " " + 
						 res.elementAt(1) + " " + 
						 res.elementAt(2)+ " " + 
						 res.elementAt(3)+ " " + 
						 res.elementAt(4)+ " " + 
						 res.elementAt(5)+ "+" +
						 res.elementAt(6);
			}
			for(int i = 0; i< ratios.size();i++) {
				if(ratios.elementAt(i)[0].equals(period)&&ratios.elementAt(i)[5].equals("")) {
					ratios.elementAt(i)[5] = restmp;
				}
			}
			saveTofile();
			DecreseRatio.mainWnd.updateHGEventsTable(ratios);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
	}

	public void initRatios(){
		
		try{

			
			File dir = new File("data");
			if (dir.exists()) {
			} else {
				dir.mkdirs();
			}
			
			File file = new File("data/" + "ratios"
					+ ".data");
			
			
			if(!file.exists()){
				fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"));
				fw.close();
			}else{
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); // 指定读取文件的编码格式，要和写入的格式一致，以免出现中文乱码,
				
				String str = null;
				
				while ((str = reader.readLine()) != null) {
					//System.out.println(str);
					String[] event = str.split(",", -1);
										
					ratios.add(event);
				}
				//fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"));			
			}
			
			
			DecreseRatio.mainWnd.updateHGEventsTable(ratios);
			
		}catch(Exception e){
			e.printStackTrace();			
		}

	}
	
	public boolean saveTofile(){
		
		try{
			File file = new File("data/" + "ratios"
					+ ".data");
			BufferedWriter fwlocal = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8"));
			
			for(int i = 0; i<ratios.size(); i++) {
				String[] event = ratios.elementAt(i);


				
				fwlocal.append(event[0] + "," + event[1] +  "," + event[2] + "," + 
						event[3] + "," + event[4]+ "," + event[5]);
				fwlocal.newLine();
				fwlocal.flush();
				//saveAlready.add(event[0]);
			}
			fwlocal.close();
			return true;
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return false;
	}

}
